/*This file is part of WZLibCP.

 *  WZLibCP is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

 *  WZLibCP is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

 *  You should have received a copy of the GNU General Public License
    along with WZLibCP.  If not, see <http://www.gnu.org/licenses/>.
		
	Author: calc0000
*/
#include "stdafx.h"
#include "WZSoundProperty.h"

#include <iostream>

#include "WZLibUtils.h"

using namespace std;

namespace WZLib{
	ctor WZSoundProperty::WZSoundProperty(WZImage* parent,string name):WZImageProperty(parent,Prop_MP3,name,Property){
		this->_data=NULL;
		this->_lenMS=0;
		this->_lenData=0;
#		ifdef WZLIB_SOUND_ENABLED
		this->_mus=NULL;
		this->_rw=NULL;
#		endif
	}
	dtor WZSoundProperty::~WZSoundProperty(){
		delete this->_data;
	}
	ErrorCode WZSoundProperty::parse(WZLib::WZBinaryReader *reader){
		reader->IncPosition(1);
		this->_lenData=reader->ReadCompressedInt();
		this->_lenMS=reader->ReadCompressedInt();
		this->_data=new byte[(sizeof(byte)*this->_lenData)+(2*sizeof(byte))];
		reader->_fread(this->_data+(2*sizeof(byte)),sizeof(byte),this->_lenData);
		this->_data[0]=0xff;
		this->_data[1]=0xf0;
		this->_parsed=true;
		return Error_NoError;
	}
	ErrorCode WZSoundProperty::play(){
#		ifdef WZLIB_SOUND_ENABLED
		if(Mix_PlayingMusic()==1)
			Mix_HaltMusic();
		if(this->_mus!=NULL)
			Mix_FreeMusic(this->_mus);
		/*if(this->_rw!=NULL)
			SDL_RWclose(this->_rw);//*/
		this->_rw=SDL_RWFromMem(this->_data,this->_lenData+(2*sizeof(byte)));
		this->_mus=Mix_LoadMUS_RW(this->_rw);
		if(this->_mus==NULL)
			return Error_WZLib_WZSoundProperty_Play_CannotLoadSample;
		Mix_PlayMusic(this->_mus,-1);
		Mix_VolumeMusic(MIX_MAX_VOLUME);
		return Error_NoError;
#		else
		return Error_NoError;
#		endif
	}
	ErrorCode WZSoundProperty::playUsingFile(){
#		ifdef WZLIB_SOUND_ENABLED
		if(Mix_PlayingMusic()==1)
			Mix_HaltMusic();
		if(this->_mus!=NULL)
			Mix_FreeMusic(this->_mus);
		FILE* f=fopen((WZConfig::imageDir+"/mus.mp3").c_str(),"wb");
		if(f==NULL)
			return Error_General_CannotOpenFile;
		fwrite(this->_data+(2*sizeof(byte)),sizeof(byte),this->_lenData,f);
		fclose(f);
		this->_mus=Mix_LoadMUS((WZConfig::imageDir+"/mus.mp3").c_str());
		if(this->_mus==NULL)
			return Error_WZLib_WZSoundProperty_Play_CannotLoadSample;
		Mix_PlayMusic(this->_mus,-1);
		Mix_VolumeMusic(MIX_MAX_VOLUME);
		return Error_NoError;
#		else
		return Error_NoError;
#		endif
	}
};